import 'package:enterprise_v6_app/app/components/custom_refresh.dart';
import 'package:enterprise_v6_app/app/components/department_regional_organization_tree/regional_organization_tree_view.dart';
import 'package:enterprise_v6_app/app/components/special_operation/custom_select_function.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/ext.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/customEndDrawer.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/Inventory_system/job_responsibilities_list_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/get_dict_all_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/common/department_user_tree_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/inventory_system/inventory_system_controller.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

///岗位履责清单
class JobPerformanceChecklistController extends GetxController {
  /// 筛选右侧栏控制Key
  final riskRightScaffoldKey = GlobalKey<ScaffoldState>();

  /// 列表刷新key
  final GlobalKey<CustomEasyRefreshListState> globalKey = GlobalKey();

  /// 选中的节点
  DepartmentUserTreeEntity selectedEntity = DepartmentUserTreeEntity();

  String searchSelect = '';
  RxString searchX = ''.obs;

  /// 状态
  RxString implementationStatus = '请选择'.obs;
  String implementationStatusId = '';

  /// 周期
  String numberOverduePeriods = '请选择';
  String numberOverduePeriodsId = '';
  List<GetDictAllEntity> currencyState = [];

  @override
  void onInit() {
    super.onInit();
    //当前完成情况(0:待完成，1已完成)
    initCurrencyState();
  }

  GetDictAllEntity? dictEntity1;
  GetDictAllEntity? dictEntity2;

  ///当前完成情况(0:待完成，1已完成)
  void selectCurrencyDangerLevelType() {
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '状态',
      dataList: currencyState,
      checkedList: [dictEntity1 ?? GetDictAllEntity()],
      isMultiple: false,
      onCallBack: (value) {
        dictEntity1 = value[0];
        implementationStatusId = value[0].getId();
        implementationStatus.value = value[0].getShowName().isEmpty ? '请选择' : value[0].getShowName();
      },
    );
  }

  Future<List<JobResponsibilitiesListEntity>> jobResponsibilitiesList(int index, int size, {String? search}) async {
    final res = await HttpUtil().generateGetRequest<List<JobResponsibilitiesListEntity>>(
      Interface.jobResponsibilitiesList,
      queryParameters: {
        'pageNum': index,
        'pageSize': size,
        'content': searchX.value, //	清单内容
        'controllable': implementationStatusId, //		当前完成情况(0:待完成，1已完成)
        'departmentId': selectedEntity.id, //		部门id
        'userId': '', //	人员id
      },
    ).execute();
    List<JobResponsibilitiesListEntity>? list = [];
    res.onSuccess((result) {
      if (result.data != null) {
        list = result.data;
      }
    });
    return list!;
  }

  /// 筛选按钮
  void onFilterButtonPressed() {
    final InventorySystemController controller = Get.find<InventorySystemController>();
    controller.filterWidget.value = _filterWidget();
    controller.riskRightScaffoldKey.currentState?.openEndDrawer();
    searchSelect = searchX.value; //向另一个地方插入值 那个地方也和这一样
    // riskRightScaffoldKey.currentState?.openEndDrawer();
  }

  /// 重置
  void reset() {
    searchX.value = '';
    searchSelect = '';
    implementationStatusId = '';
    implementationStatus.value = '请选择';

    numberOverduePeriodsId = '';
    numberOverduePeriods = '请选择';
    Get.find<InventorySystemController>().riskRightScaffoldKey.currentState?.closeEndDrawer();
    selectedEntity = DepartmentUserTreeEntity();
    globalKey.currentState!.onRefresh();
    update();
  }

  /// 确定
  void confirm() {
    Get.back();
    searchX.value = searchSelect;
    globalKey.currentState!.onRefresh();
    update();
  }

  ///历史执行情况
  void clickHistoricalExecutionStatus(JobResponsibilitiesListEntity item) {
    Get.toNamed(AppRoutes.jobHistoricalExecutionStatusPage, arguments: item.id); //	履责工作内容id
  }

  ///最新执行详情
  void jobLatestExecutionDetails(JobResponsibilitiesListEntity item) {
    Get.toNamed(AppRoutes.jobLatestExecutionDetailsPage, arguments: {'checkTaskId': item.id});
  }

  void refreshPage() {
    globalKey.currentState?.onRefresh();
  }

  void initCurrencyState() {
    currencyState.clear();
    final GetDictAllEntity getDictAllEntity = GetDictAllEntity();
    getDictAllEntity.id = '0';
    getDictAllEntity.dictionaryLabel = '待完成';
    currencyState.add(getDictAllEntity);

    final GetDictAllEntity getDictAllEntity2 = GetDictAllEntity();
    getDictAllEntity2.id = '1';
    getDictAllEntity2.dictionaryLabel = '已完成';
    currencyState.add(getDictAllEntity2);
  }

  Widget _filterWidget() {
    return CustomEndDrawer(
      centerContext: Column(
        children: [
          _selectType(
              '清单内容',
              input: Container(
                  height: 38.w,
                  padding: EdgeInsets.symmetric(horizontal: 12.w),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: Colors.white,
                      border: Border.all(color: const Color(0xffF0F0F0), width: 1.w),
                      borderRadius: BorderRadius.all(Radius.circular(8.w))),
                  child: Row(
                    children: [
                      Expanded(
                          child: Obx(() => TextField(
                              keyboardType: TextInputType.text,
                              textInputAction: TextInputAction.done,
                              controller:
                              TextEditingController(text:searchX.value.isNotEmpty ?searchX.value :searchSelect),
                              onChanged: (value) {
                                searchSelect = value;
                              },
                              style: TextStyle(color: const Color(0xff222222), fontWeight: FontWeight.w400, fontSize: 14.sp),
                              decoration: InputDecoration(
                                counterText: '',
                                //防止适配不居中
                                isCollapsed: true,
                                border: const OutlineInputBorder(borderSide: BorderSide.none),
                                contentPadding: EdgeInsets.only(left: 8.w),
                                hintText: '请输入搜索内容',
                                hintStyle: TextStyle(fontSize: 12.sp, fontWeight: FontWeight.w400, color: const Color(0xffA0A7B5)),
                              ))))
                    ],
                  )),

          ),
          Obx(() =>  _selectType('当前完成情况')),
          DepartmentRegionalOrganizationTreePage(
            selectedEntity: selectedEntity,
            onCallBack: (DepartmentUserTreeEntity entity) {
            selectedEntity = entity;
            },
          ),
        ],
      ),
      reset: reset,
      confirm: confirm,
    );
  }

  Widget _selectType(String firstName,{Widget? input}) {
    return Column(
      children: [
        Align(
          alignment: Alignment.centerLeft,
          child: Text(
            firstName,
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.w400,
              color: const Color(0xFF262F38),
            ),
          ),
        ),
        AppGaps.vGap16,
        input ??
            Container(
              height: 38.w,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(width: 1.w, color: const Color(0xFFE3E7EE)),
              ),
              child: Row(
                children: [
                  AppGaps.hGap20,
                  Expanded(
                    child: Text(
                      _selectName(firstName),
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: const Color(0xFFA0A7B5),
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ),
                  SvgPicture.asset(AppImages.icon_filter_right_arrow),
                  AppGaps.hGap20,
                ],
              ),
            ).clickOnce(() {
              if (firstName == '当前完成情况') {
              selectCurrencyDangerLevelType();
              } else if (firstName == '逾期次数周期') {
                // controller.selectCurrencyTrainingChannelsType();
              }
            }),
        AppGaps.vGap16,
      ],
    );
  }
  String _selectName(String firstName) {
    if (firstName == '当前完成情况') {
      return implementationStatus.value;
    } else if (firstName == '逾期次数周期') {
      return numberOverduePeriods;
    }
    return '';
  }

}
